﻿<!-- #layout name=default -->
<div id="main" class="offset-top">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <div class="page-header">
        <h1 class="title">Register a domain</h1>
      </div>
      <div v-if="!confirm">
        <div class="form-group" :class="{'has-error':error}">
          <div class="input-group">
            <input
              type="text"
              placeholder="domain name keyword"
              name="domain"
              @keyup.enter="search"
              class="form-control input-lg"
              v-model="domain"
              v-kb-tooltip:top.manual.error="error"
              @click="error=''"
            />
            <span class="input-group-btn">
              <button type="button" @click="search" class="btn blue btn-lg"
                >Search</button
              >
            </span>
          </div>
        </div>
      </div>
      <table
        v-if="!confirm&&suggests.length"
        class="table table-striped table-hover"
      >
        <caption v-if="!available">Suggested domains</caption>
        <thead>
          <tr>
            <th>Domain</th>
            <th>Price</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="($data,index) in suggests" :key="index">
            <td>{{$data.domain}}</td>
            <td>
              <template v-if="$data.price > 0">
                <span v-html="currencySymbol + $data.price"></span>
                <span>First year</span>
              </template>
              <template v-else>
                Unknow
              </template>
            </td>
            <td>
              <div v-if="$data.price > 0" class="btn-group pull-right">
                <button
                  type="button"
                  class="btn btn-xs green"
                  @click="select($data,1)"
                  >Buy it</button
                >
                <button
                  type="button"
                  class="btn btn-xs green dropdown-toggle"
                  data-toggle="dropdown"
                  ><i class="fa fa-angle-down"></i
                ></button>
                <ul class="dropdown-menu" role="menu">
                  <li v-for="(item,i) in yearOptions($data.price)" :key="i">
                    <a
                      href="javascript:;"
                      @click="select($data,i)"
                      v-html="formatYearPrice(item)"
                    ></a>
                  </li>
                </ul>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <h4
        style="text-align: center;margin: 50px;"
        v-if="!suggests.length&&posted"
        >No domain found</h4
      >
      <template v-if="confirm">
        <table class="table">
          <thead>
            <tr>
              <th>Domain</th>
              <th>Duration</th>
              <th>Unit price</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{{domain}}</td>
              <td>{{formatedYear()}}</td>
              <td>{{unitPrice}}</td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td
                ><span>Total</span>:
                <strong v-html="currencySymbol + ' ' + totalPrice"></strong
              ></td>
            </tr>
          </tbody>
        </table>
        <div v-if="confirm" class="panel panel-default">
          <div class="panel-heading">
            <h6 class="panel-title">Payment</h6>
          </div>
          <div class="panel-body">
            <div class="form-group">
              <div class="radio">
                <label>
                  <input
                    type="radio"
                    value="wechat"
                    v-model="payment"
                    :disabled="totalPrice>balance"
                  />
                  <span>Balance</span>:
                  <span
                    v-html="currencySymbol + ' ' + (balance*100)/100"
                  ></span>
                  <span v-if="totalPrice > balance"
                    >(Insufficient balance)</span
                  >
                </label>
              </div>
              <div class="radio">
                <label>
                  <input type="radio" value="wechat" v-model="payment" />
                  <span>WeChat payment</span>:
                  <span v-html="currencySymbol + ' ' + totalPrice"></span>
                </label>
              </div>
              <div class="radio">
                <label>
                  <input type="radio" value="paypal" v-model="payment" />
                  <span>Paypal payment</span>:
                  <span v-html="currencySymbol + ' ' + totalPrice"></span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </template>

      <ul class="pager">
        <li class="next" v-if="confirm"
          ><a class="btn green" href="javascript:;" @click="submit"
            >Pay now!</a
          ></li
        >
        <li class="previous"
          ><a
            class="btn gray"
            href="javascript:;"
            v-if="confirm"
            @click="confirm=false"
            >Cancel</a
          ></li
        >
      </ul>
    </div>
  </div>
  <cashier-modal></cashier-modal>
  <div
    id="payment-qrcode-container"
    class="modal fade"
    data-backdrop="static"
    v-kb-modal="showQrcode"
  >
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">{{domain}}</h4>
        </div>
        <div class="modal-body">
          <h2>Wechat Pay</h2>
          <div id="qrcode"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/View/Market/Scripts/components/CashierModal.js",
      "/_Admin/Scripts/lib/jquery.qrcode.min.js"
    ]);

    var self = new Vue({
      el: "#main",
      data: function() {
        return {
          confirm: false,
          domain: "",
          suggests: [],
          available: false,
          currencySymbol: "&yen;",
          years: 0,
          unitPrice: -1,
          payment: "",
          balance: 0.0,
          organizationId: "",
          showQrcode: false,
          paymentId: "",
          interval: null,
          posted: false,
          error: ""
        };
      },
      mounted: function() {
        Kooboo.Organization.getOrg().then(function(res) {
          if (res.success) {
            self.organizationId = res.model.id;
            self.balance = res.model.balance;
          }
        });

        Kooboo.EventBus.subscribe("kb/market/cashier/done", function() {
          setTimeout(function() {
            location.href = Kooboo.Route.Domain.IndexPage;
          }, 300);
        });
      },
      computed: {
        totalPrice: function() {
          return +(this.unitPrice * this.years);
        }
      },
      methods: {
        search: function() {
          var validResult = Kooboo.validField(self.domain.trim(), [
            { required: Kooboo.text.validation.required },
            {
              pattern: /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/,
              message: Kooboo.text.validate.domainInvalid
            }
          ]);
          self.error = validResult.msg;
          if (!validResult.valid) return;
          Kooboo.Domain.searchDomain({
            domain: self.domain.trim()
          }).then(function(data) {
            self.suggests = data.model;
            self.posted = true;
          });
        },
        select: function(item, amount) {
          Kooboo.Order.domain({
            domainName: item.domain,
            year: amount + 1
          }).then(function(res) {
            if (res.success) {
              Kooboo.EventBus.publish(
                "kb/market/component/cashier/show",
                res.model
              );
            }
          });
        },
        yearOptions: function(prices) {
          var arr = [];
          for (var i = 1, l = 3; i <= l; i++) {
            arr.push({
              value: prices,
              key: i
            });
          }
          return arr;
        },
        formatYearPrice: function(v) {
          return (
            self.currencySymbol +
            +v.key * +v.value +
            " / " +
            v.key +
            " " +
            (v.key > 1
              ? Kooboo.text.site.domain.years
              : Kooboo.text.site.domain.year)
          );
        },
        formatedYear: function() {
          var y = self.years;
          return y > 1
            ? y + " " + Kooboo.text.site.domain.years
            : y + " " + Kooboo.text.site.domain.year;
        },
        submit: function() {
          Kooboo.Domain.payDomain({
            name: self.domain,
            years: self.years,
            organizationId: self.organizationId,
            paymentMethod: self.payment
          }).then(function(data) {
            var m = data.model;
            if (m.success === false) {
              alert(m.errorMessage);
            } else if (m.success === true && m.paid === true) {
              alert("Paid by balance!");
              location.href = "/_Admin/Domains";
            } else if (self.payment == "paypal") {
              window.location.href = m.approvalUrl;
            } else {
              $("#qrcode").qrcode(m.qrcode);
              self.showQrcode = m.success;
              self.paymentId = m.paymentId;
              self.checkStatus(m.paymentId);

              self.interval = setInterval(function() {
                self.checkStatus(m.paymentId);
              }, 3000);
            }
          });
        },
        checkStatus: function(paymentId) {
          if (!paymentId) {
            return;
          }
          if (!paySuccess) {
            Kooboo.Domain.getPaymentStatus({
              organizationId: self.organizationId,
              paymentId: paymentId
            }).then(function(data) {
              if (data.model.success) {
                paySuccess = true;
                clearInterval(self.interval);
                location.href = "/_Admin/Domains";
              }
            });
          }
        }
      }
    });
  })();
</script>
<script src="/_Admin/View/Market/Scripts/Kooboo.Market.js"></script>
